package com.weixin.server.sm.impl;

import com.weixin.domain.sm.Employee;
import com.weixin.exception.BusinessException;
import com.weixin.mapper.template.sm.EmployeeMapper;
import com.weixin.request.RegisterCustomerRequest;
import com.weixin.response.LoginResponse;
import com.weixin.server.sm.EmployeeService;
import com.weixin.util.PasswordHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author lc
 * @email 389125111@qq.com
 * @create 2018-03-23 15:48
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public LoginResponse findByUsername(String username) {
        Employee employee = employeeMapper.selectOne(new Employee() {{
            this.setUsername(username);
        }});

        if (null == employee) {
            return null;
        }
        LoginResponse response = new LoginResponse() {{
            this.setUsername(employee.getUsername());
            this.setId(employee.getId());
        }};
        return response;
    }

    @Override
    public boolean registerCustomer(RegisterCustomerRequest request) {
        List<Employee> employees = employeeMapper.select(new Employee() {{
            this.setUsername(request.getUsername());
            this.setDelTag(false);
        }});
        if (null != employees || employees.size() > 0) {
            throw new BusinessException(2000, "用户存在");
        }
        String salt = PasswordHelper.getSalt();
        String encryptPwd = PasswordHelper.encryptPwd(request.getPassword(), salt);
        employeeMapper.insertUseGeneratedKeys(new Employee() {{
            this.setUsername(request.getUsername());
            this.setPassword(encryptPwd);
            this.setSalt(salt);
            this.setCreateDate(new Date());
            this.setDelTag(false);
        }});
        return true;
    }

    @Override
    public void update(List<Employee> employees) {
        employeeMapper.updateTest(employees);
    }

}
